package logic

import (
	"context"
	"gitee.com/Cauchy_AQ/vxopen/model/mongodb"
	"gitee.com/Cauchy_AQ/vxopen/rpc/transform/internal/errors"
	"gitee.com/Cauchy_AQ/vxopen/utils"

	"gitee.com/Cauchy_AQ/vxopen/rpc/transform/internal/svc"
	"gitee.com/Cauchy_AQ/vxopen/rpc/transform/transform"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserPasswordLogic {
	return &UserPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserPasswordLogic) UserPassword(in *transform.UserPasswordReq) (*transform.UserPasswordResp, error) {
	mongoClient := mongodb.GetMongoInstance(l.svcCtx.Config.ModelConfig)
	var err error
	var user *mongodb.User
	if len(in.Openid) > 0 {
		user, err = mongoClient.UserCol.FindOneByOpenId(context.Background(), in.Openid)
	} else {
		user, err = mongoClient.UserCol.FindOneByMobile(context.Background(), in.Mobile)
	}
	if err != nil {
		return nil, err
	}
	// 1. 校验原密码正确性
	if len(user.Password) > 0 && !utils.CheckPassword(in.OldPassword, user.Password) {
		return nil, errors.ErrorUserOldPasswd
	}
	user.Password = utils.EncryptPassword(in.NewPassword)
	// 2. 更新密码
	if len(in.Openid) > 0 {
		_, err = mongoClient.UserCol.UpdatePasswdByOpenId(context.Background(), user)
	}
	if err != nil {
		return nil, err
	}
	if len(in.Mobile) > 0 {
		_, err = mongoClient.UserCol.UpdatePasswdByMobile(context.Background(), user)
	}
	if err != nil {
		return nil, err
	}

	return &transform.UserPasswordResp{}, nil
}
